package com.wlw.config;

import com.wlw.listener.CheckParam;
import com.wlw.listener.CheckToken;
import com.wlw.service.RedisServiceImpl;
import com.wlw.util.response.CommonResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

/**
 * 验证登录切面
 *
 * ClassName: CheckTokenAop
 *

 */
@Component
@Aspect
public class CheckTokenAop {
    //	@Autowired
//	CheckTokenAopService checkTokenAopService;
    @Autowired
    private RedisServiceImpl redisServiceImpl;
    /**
     * @param joinPoint
     * @throws Throwable
     * @return BaseResult

     */
    @Around("@annotation(com.wlw.listener.CheckToken)")
    public CommonResponse around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 当token为null的时候说明未登录
        CommonResponse commonResponse =new CommonResponse();
        String token = getOperatorIdByToken(joinPoint);
        if (token == null){
            commonResponse.setMessage("APP未传身份字段");
            commonResponse.setCode(500);
            return commonResponse;
        }
        if(!redisServiceImpl.existKey(token)){
            commonResponse.setMessage("登录失效,请重新登录");
            commonResponse.setCode(501);
            return commonResponse;
        }
        redisServiceImpl.refreshKeyExpire(token);
        // 验证当前用户是否已经在其他手机登录
//		if (checkTokenAopService.checkOperatorTokenIsChange(token))
//			return new BaseResult(BaseCode.TOKEN_CHANGE, BaseCode.TOKEN_CHANGE_MSG, null);
//
//		synchronized (this) {
//			// 检测app相关信息，并且保存
//			checkTokenAopService.checkAndUpdateAppInfo(joinPoint, token);
//		}

        // 如果登录，则返回方法的返回值
        return (CommonResponse) joinPoint.proceed();
    }
    public String getOperatorIdByToken(JoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();

        // 获取方法注解
        CheckToken checkToken = ms.getMethod().getAnnotation(CheckToken.class);

        if (checkToken == null)
            return null;

        String token = null;
        Annotation[][] anno = ms.getMethod().getParameterAnnotations();
        for (int i = 0; i < anno.length; i++) { // 循环参数列表
            for (int j = 0; j < anno[i].length; j++) { // 循环某上参数上的注解
                if (anno[i][j] instanceof CheckParam && ((CheckParam) anno[i][j]).value().equals(checkToken.value())) {
                    token = joinPoint.getArgs()[i] == null ? null : (String) joinPoint.getArgs()[i];
                }
            }
        }
        // || StringUtil.isEmpty(redisUtil.get(token))
        if (token == null)
            token = null;
        return token;
    }
}
